package cn.gdchent.springbootsecurity.utils;

import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CsvFileUtil {

    public static void readCS1() {
        String srcPath = "D:\\www\\data.csv";
        String charset = "utf-8";
        try (CSVReader csvReader = new CSVReaderBuilder(new BufferedReader(new InputStreamReader(new FileInputStream(new File(srcPath)), charset))).build()) {
            Iterator<String[]> iterator = csvReader.iterator();
            while (iterator.hasNext()) {
                Arrays.stream(iterator.next()).forEach(System.out::print);
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void readCSV2(){
        File file=new File("D:\\www\\data.csv");
        if(file.exists()){
            System.out.println("文件存在");
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader(file));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            String line = "";
            String everyLine = "";
            int i=0;
            try {
                List<String> allString = new ArrayList<>();
                while ((line = br.readLine()) != null) // 读取到的内容给line变量
                {
                    if(i==0){
                        line=line.replaceAll(" ","_");//将空格转为下划线
                        System.out.println("第一行："+line);
                    }
                    i++;
                    everyLine = line;
                    System.out.println(everyLine);
                    allString.add(everyLine);
                }
                System.out.println("csv表格中所有行数：" + allString.size());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
